<template>
  <div class="system-menu-container">
		<div class="system-user-search mb15">
			<el-form :model="param" :inline="true" ref="queryFormRef" @keyup.enter.native="loadList">
				<el-row>
              		<el-col :span="24">
						<el-form-item label="执行器" prop="jobGroup">
							<el-select v-model="param.jobGroup" placeholder="请选择执行器">
								<el-option :key="0" :value="0" label="全部"></el-option>
								<el-option v-for="(item) in jobGroups" :key="item.id" :value="item.id" :label="item.title"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="调度状态"  prop="logStatus">
							<el-select v-model="param.logStatus" placeholder="启动状态">
								<el-option :key="-1" :value="-1" label="全部"></el-option>
								<el-option :key="1" :value="1" label="成功"></el-option>
								<el-option :key="2" :value="2" label="失败"></el-option>
								<el-option :key="3" :value="3" label="进行中"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="描述" prop="jobDesc">
							<el-input v-model="param.jobDesc" placeholder="任务描述" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="" prop="filterTime">
							<el-date-picker v-model="param.filterTime" type="datetimerange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"></el-date-picker>
						</el-form-item>
						<el-button type="primary" @click="loadList">
							<el-icon>
								<ele-Search />
							</el-icon>
							查询
						</el-button>
						<el-button type="primary" @click="reSetForm(queryFormRef)">
							<el-icon>
								<ele-Refresh />
							</el-icon>
							重置
						</el-button>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<el-table :data="dataList" border v-loading="listLoading" @selection-change="selectionChangeHandle" style="width: 100%;">
			<el-table-column prop="jobGroup" label="执行器" :formatter="formatJobGroup"></el-table-column>
			<el-table-column prop="jobDesc" label="任务描述"></el-table-column>
			<el-table-column prop="executorAddress" label="执行器地址"></el-table-column>
			<el-table-column prop="triggerTime" label="调度时间" width="150" ></el-table-column>
			<el-table-column prop="triggerCode" label="调度结果" width="100"  :formatter="formatTriggerCode"></el-table-column>
			<el-table-column label="调度备注" width="100">
			<template #default="scope">
				<el-button type="primary" link @click="showTriggerMsg(scope.row)" >查看</el-button>
				<!-- <el-popover placement="top-start" trigger="click" ref="triggerMsgPopover" >
				<div v-html="scope.row.triggerMsg"></div>
				</el-popover >-->
			</template>
			</el-table-column>
			<el-table-column prop="handleTime" label="执行时间" width="150" ></el-table-column>
			<el-table-column prop="handleCode" label="执行结果" width="100" :formatter="formatHandleCode"></el-table-column>
			<el-table-column label="执行备注" width="100">
			<template #default="scope">
				<el-button type="primary" link @click="showHandleCode(scope.row)" >查看</el-button>
			</template>
			</el-table-column>
			<el-table-column label="操作">
			<template #default="scope">
				<el-button v-if="scope.row.triggerCode == 200 || scope.row.handleCode != 0" type="primary" link @click="showlogDetail(scope.row)">执行日志</el-button>
				<el-button v-if="scope.row.handleCode == 0" type="primary" link @click="killJobIns(scope.row)">终止任务</el-button>
			</template>
			</el-table-column>
		</el-table>
		<el-pagination
			@size-change="onHandleSizeChange"
			@current-change="onHandleCurrentChange"
			:pager-count="5"
			:page-sizes="[10, 50, 200]"
			v-model:current-page="param.page"
			background
			v-model:page-size="param.limit"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total" small>
		</el-pagination>
		<el-dialog  ref="addOrUpdate" title="执行日志"  v-model="dialogVisible" width="40%" class="customDialog">
			<el-button size="mini" icon="el-icon-refresh" @click="refreshLogDetail()">刷新</el-button>
			<div v-html="logDetailMsg"></div>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, watch, onMounted, defineComponent } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElNotification } from 'element-plus'
// import {cron} from 'vue-cron'
//局部引入
import {scheduleApi} from '/@/api/scheduleapi'
export default defineComponent({
	components:{},
	setup () {
		const queryFormRef = ref<FormInstance>()
		const ruleFormRef = ref();
		const state = reactive({
			listLoading: false,
			dataList: [],
			total: 0,
			totalSelect: 0,
			jobGroups: [],
			jobGroupMap: {},
			param: {
				page: 1,
				limit: 10,
				jobGroup: 0,
				logStatus: -1,
				jobDesc: '',
				filterTime: ''
			},
			dataListSelections: [],
			dialogVisible: false,
			ExecutorRouteStrategyEnum: {
				'FIRST': '第一个',
				'LAST': '最后一个',
				'ROUND': '轮询',
				'RANDOM': '随机',
				'CONSISTENT_HASH': '一致性HASH',
				'LEAST_FREQUENTLY_USED': '最不经常使用',
				'LEAST_RECENTLY_USED': '最近最久未使用',
				'FAILOVER': '故障转移',
				'BUSYOVER': '忙碌转移',
				'SHARDING_BROADCAST': '分片广播'
			},
			GlueTypeEnum: {
				'BEAN': 'BEAN',
				'GLUE_GROOVY': 'GLUE(Java)',
				'GLUE_SHELL': 'GLUE(Shell)',
				'GLUE_PYTHON': 'GLUE(Python)',
				'GLUE_PHP': 'GLUE(PHP)',
				'GLUE_NODEJS': 'GLUE(Nodejs)',
				'GLUE_POWERSHELL': 'GLUE(PowerShell)'
			},
			ExecutorBlockStrategyEnum: {
				'SERIAL_EXECUTION': '单机串行',
				'DISCARD_LATER': '丢弃后续调度',
				'COVER_EARLY': '覆盖之前调度'
			},
			MisfireStrategyEnum: {
				'DO_NOTHING': '忽略',
				'FIRE_ONCE_NOW': '立即执行一次'
			},
			ScheduleTypeEnum: {
				'NONE': '无',
				'CRON': 'CRON表达式',
				'FIX_RATE': '固定速度'
			},
			fromLineNum: 1,
			pullFailCount: 0,
			logDetailMsg: '',
			rowThis:{}
		})

		// 页面加载时
		onMounted(() => {
			initJobGrous()
			// 列表查询
			loadList()
		})

		const initJobGrous = () => {
			scheduleApi().getXxlJobGroupList().then(data => {
				if (data && data.code === 0) {
					state.jobGroups = data.list
					data.list.forEach(item => {
						state.jobGroupMap[item.id] = item.title
					})
				} else {
					this.jobGroups = []
				}
			}).catch(()=>{
				state.jobGroups = []
			}).finally(()=>{
			})
		}
		//查询
		const loadList = () => {
			state.listLoading = true
			scheduleApi().getXxlJobLogList(state.param).then(data => {
				if (data && data.code === 0) {
					state.dataList = data.page.list
					state.total = data.page.totalCount
				} else {
					state.dataList = []
					state.total = 0
				}
			}).catch(() => {
			}).finally(() => {
				state.listLoading = false
			})
		}

		//重置
		const reSetForm = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.resetFields()
			state.param.page = 1
			loadList()
		}
		// 分页改变
		const onHandleSizeChange = (val: number) => {
			state.param.limit = val;
			loadList()
		}
		// 分页改变
		const onHandleCurrentChange = (val: number) => {
			state.param.page = val;
			loadList()
		}
		const selectionChangeHandle = (val: any) => {
			state.dataListSelections = val
		}

		const formatJobGroup = (row, column, cellValue, index) => {
			return state.jobGroupMap[cellValue]
		}

		const formatTriggerStatus = (row, column, cellValue, index) => {
			return cellValue ? '运行' : '停止';
		}
		const formatTriggerCode = (row, column, cellValue, index) => {
			return cellValue == 200 ? '成功' : '失败';
		}
		const showTriggerMsg = (row: any) => {
			ElNotification({
				message: row.triggerMsg,
				type: 'info',
				duration: 0,
				position: 'top-right',
				dangerouslyUseHTMLString: true
			})
		}
		const showHandleCode = (row: any) => {
			ElNotification({
				message: row.handleCode,
				type: 'info',
				duration: 0,
				position: 'top-right',
				dangerouslyUseHTMLString: true
			})
		}
		const showlogDetail = (row: any) => {
			state.dialogVisible = true
			state.rowThis = row
			scheduleApi().logDetailCatInfo(row.executorAddress, row.triggerTime, row.id, state.fromLineNum).then(data => {
				if(data && data.code === 0){
					// console.log(data.logResult)
					if(!data.logResult)
						return;
					if (state.fromLineNum != data.logResult.content.fromLineNum) {
						return
					}
					if (state.fromLineNum > data.logResult.content.toLineNum ) {
						// valid end
						if (data.logResult.content.end) {
							state.logDetailMsg = state.logDetailMsg + '<br><span style="color: green;">[Rolling Log Finish]</span>'
							return
						}
						return
					}
					state.fromLineNum = data.logResult.content.toLineNum + 1
					state.logDetailMsg  = state.logDetailMsg + data.logResult.content.logContent
					// console.log(this.logDetailMsg)
					state.pullFailCount = 0
				}
			})
		}
		const killJobIns = (row: any) => {
			//强制终止正在执行的任务
			scheduleApi().killJobIns(row.id).then(data => {
				if (data && data.code === 0) {
					ElMessage.success('终止任务成功')
				} else {
					ElMessage.error(data.msg)
				}
			}).catch(()=>{
				ElMessage.error('终止任务失败')
			})
		}
		watch(() => state.dialogVisible, (val:boolean) => {
			if(!val){
				state.fromLineNum = 1
				state.pullFailCount = 0
				state.logDetailMsg = ''
				state.rowThis = {}
			}
		})

		return {
			loadList,
			reSetForm,
			queryFormRef,
			selectionChangeHandle,
			ruleFormRef,
			formatJobGroup,
			formatTriggerStatus,
			initJobGrous,
			onHandleSizeChange,
			onHandleCurrentChange,
			formatTriggerCode,
			showTriggerMsg,
			showHandleCode,
			showlogDetail,
			killJobIns,
			...toRefs(state),
		}
	}
})
</script>

<style>

</style>